// =============================
// AI 医生：可拖拽图标
// =============================
const aiIcon = document.getElementById("aiDoctorIcon");
let isDragging = false;
let offsetX, offsetY;

aiIcon.addEventListener("mousedown", function(e) {
    isDragging = true;
    offsetX = e.clientX - aiIcon.getBoundingClientRect().left;
    offsetY = e.clientY - aiIcon.getBoundingClientRect().top;
});

document.addEventListener("mousemove", function(e) {
    if (!isDragging) return;

    aiIcon.style.right = "auto";
    aiIcon.style.bottom = "auto";

    aiIcon.style.left = (e.clientX - offsetX) + "px";
    aiIcon.style.top = (e.clientY - offsetY) + "px";
});

document.addEventListener("mouseup", function() {
    isDragging = false;
});

// =============================
// AI 医生：对话框显示 & 隐藏
// =============================
const aiDialog = document.getElementById("aiDoctorDialog");
const closeBtn = document.getElementById("closeAiDoctor");

aiIcon.addEventListener("click", function() {
    aiDialog.classList.remove("hidden");
});

closeBtn.addEventListener("click", function() {
    aiDialog.classList.add("hidden");
});

// =============================
// AI 医生：发送消息
// =============================
const aiInput = document.getElementById("aiInput");
const aiSendBtn = document.getElementById("aiSendBtn");
const aiChat = document.getElementById("aiChatBox");

// 向聊天框追加消息
function addMessage(text, sender="user") {
    const div = document.createElement("div");
    div.className = "message-container flex items-center mb-3";

    const avatar = document.createElement("div");
    avatar.className = sender === "ai" ? "avatar ai-avatar" : "avatar user-avatar";
    avatar.innerHTML = sender === "ai" ? "🤖" : "👤";  // AI 和 用户的头像

    const bubble = document.createElement("div");
    bubble.className = sender === "ai" ? "message-bubble ai-bubble" : "message-bubble user-bubble";
    bubble.innerText = text;

    div.appendChild(avatar);
    div.appendChild(bubble);
    aiChat.appendChild(div);
    aiChat.scrollTop = aiChat.scrollHeight;
}

// 点击发送按钮
aiSendBtn.addEventListener("click", sendAiQuestion);
aiInput.addEventListener("keypress", function(e){
    if (e.key === "Enter") sendAiQuestion();
});

// 发送请求到后端
async function sendAiQuestion() {
    const question = aiInput.value.trim();
    if (!question) return;

    addMessage("你：" + question, "user");
    aiInput.value = "";

    addMessage("AI 正在思考...", "ai");

    try {
        const res = await fetch("/ai/ask", {
            method: "POST",
            headers: {"Content-Type": "application/json"},
            body: JSON.stringify({ question })
        });

        const data = await res.json();
        aiChat.removeChild(aiChat.lastChild); // 移除“AI 正在思考...”
        addMessage("AI：" + (data.answer || "AI 暂时无法回答"), "ai");

    } catch (err) {
        aiChat.removeChild(aiChat.lastChild);
        addMessage("AI 服务异常，请稍后再试。", "ai");
    }
}
